package com.lvkerry.orderfood.service.impl;


import com.lvkerry.orderfood.api.ApiBean;
import com.lvkerry.orderfood.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import static com.lvkerry.orderfood.global.ConstCodeKt.API_ERROR;
import static com.lvkerry.orderfood.global.ConstCodeKt.API_SUCCESS;

/**
 * @author Kerry
 */
@Service
public class ResourceServiceImpl implements ResourceService {


    private final ResourceLoader resourceLoader;

    @Value("${server.upload.path}")
    private String baseSaveImagePath;

    @Autowired
    public ResourceServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @Override
    public ApiBean saveResource(MultipartFile file) throws IOException {

        boolean image = file.getContentType().contains("image");

        if (!image) {
            return new ApiBean.Builder().setMessage("File type is not match..").setStatus(API_ERROR).build();
        }
        final int pos = file.getContentType().lastIndexOf("/");
        String fileName = UUID.randomUUID().toString() + "." + file.getContentType().substring(pos + 1).trim();

        File checkFolder = new File(baseSaveImagePath);
        if (!checkFolder.exists()) {
            boolean mkdirs = checkFolder.mkdirs();
        }

        Path filePath = Paths.get(baseSaveImagePath, fileName);
        Files.copy(file.getInputStream(), filePath);
        return new ApiBean.Builder().setStatus(API_SUCCESS).setMessage("success upload").setData(fileName).build();
    }

    @Override
    public Resource getResource(String filename) {
        return resourceLoader.getResource("file:" + Paths.get(baseSaveImagePath, filename).toString());
    }
}
